<template>
  <Modal :value="visible"
         :title="title"
         @on-visible-change="onChangeVisible"
         width="780">
    <div class="flex ">
      <div class="menu">
        <div v-for="(item,index) in menuArr"
             :key='index'
             class="cursor-pointer"
             :class="{'current-menu':currentIndex == index}"
             @click.stop="onClickMenuItem(index)">
          {{item.name}}
        </div>
      </div>
      <div class="item-menu"
           v-if="currentIndex == 0">
        <div class=" cursor-pointer"
             v-for="(item,index) in carItemMenuArr"
             :key='index'
             :class="{'current-menu':currentCarItemIndex == index}"
             @click.stop="onClickCarItemMenuItem(index)">{{item.name}}
        </div>
      </div>
      <div class="item-menu"
           v-if="currentIndex == 3">
        <div class=" cursor-pointer"
             v-for="(item,index) in processingStationMenuArr"
             :key='index'
             :class="{'current-menu':currentProcessingStationIndex == index}"
             @click.stop="onClickProcessingStationMenuItem(index)">{{item.name}}
        </div>
      </div>

      <div class="item-menu"
           v-if="currentIndex == 4">
        <div class=" cursor-pointer"
             v-for="(item,index) in itemMenusArr"
             :key='index'
             :class="{'current-menu':currentItemIndex == index}"
             @click.stop="onClickItemMenuItem(index)">{{item.name}}
        </div>
      </div>
      <div class="modal-cont flex-1">
        <ul class="form-ul">
          <li class="form-ul-li half"
              v-if="currentIndex == 0">
            <p class="li-title">所属机构：</p>
            <MyTreeSelect :value="departmentName"
                          placeholder="所属机构"
                          clearable
                          :data="departmentTreeArr"
                          search
                          style="width:100%"
                          @onSelectChange="onChangeDepartment">
            </MyTreeSelect>
          </li>
          <li class="form-ul-li"
              v-if="currentIndex == 0">
            <p class="li-title">作业车辆：</p>
            <!-- 固定作业为单选，机动作业为多选 -->
            <MyTreeSelect :value="car"
                          placeholder="作业车辆"
                          :disabled='carDisabled'
                          :data="carTreeArr"
                          search
                          style="width:100%;"
                          class="half"
                          @onSelectChange="onChangeSelectCar">
            </MyTreeSelect>
          </li>
          <div class="car"
               v-if="currentIndex == 0">
            <div class="car-item"
                 v-for="(item,index) in carList"
                 :key="index"
                 :title="item.name"
                 @click.stop="">
              <span class="line1">{{item.name}}</span>
              <Icon custom="i-icon icon-guanbi"
                    size="16"
                    color="#6a6b75"
                    @click.stop="onClickDeleteCar(index)" />
            </div>
          </div>
          <li class="form-ul-li half"
              v-if="currentIndex == 1">
            <p class="li-title">作业班组：</p>
            <MyTreeSelect :value="group"
                          placeholder="班组名称"
                          :data="groupTreeArr"
                          search
                          style="width:100%;"
                          @onSelectChange="onChangeGroup">
            </MyTreeSelect>
          </li>
          <li class="form-ul-li half"
              v-if="currentIndex == 2">
            <p class="li-title">作业规则：</p>
            <Select v-model="ruleId"
                    label-in-value
                    @on-change="onChangeRule"
                    clearable>
              <Option v-for="item in ruleArr"
                      :value="item.workRuleId"
                      :key="item.workRuleId">{{ item.ruleName }}</Option>
            </Select>
          </li>
          <li class="form-ul-li"
              v-if="currentIndex == 3">
            <p class="li-title">处理站：</p>
            <MyTreeSelect ref="disposeTreeSelect"
                          :value="dispose"
                          placeholder="处理站"
                          :data="disposeTreeArr"
                          search
                          checked
                          clearable
                          style="width:100%;"
                          @onCheckChange="onChangeDispose">
            </MyTreeSelect>
          </li>
          <div class="car"
               v-if="currentIndex == 3">
            <div class="car-item"
                 v-for="(item,index) in disposeList"
                 :key="index"
                 @click.stop="">
              <span class="line1">{{item.name}}</span>
              <Icon custom="i-icon icon-guanbi"
                    size="16"
                    color="#6a6b75"
                    @click.stop="disposeList.splice(index,1)" />
            </div>
          </div>
          <li class="form-ul-li"
              v-if="currentIndex == 4">
            <p class="li-title">中转站：</p>
            <MyTreeSelect :value="gather"
                          placeholder="中转站"
                          :data="gatherTreeArr"
                          search
                          checked
                          clearable
                          style="width:100%;"
                          @onCheckChange="onChangeGather">
            </MyTreeSelect>
          </li>
          <div class="car"
               v-if="currentIndex == 4">
            <div class="car-item"
                 v-for="(item,index) in gatherList"
                 :key="index"
                 @click.stop="">
              <span class="line1">{{item.name}}</span>
              <Icon custom="i-icon icon-guanbi"
                    size="16"
                    color="#6a6b75"
                    @click.stop="gatherList.splice(index,1)" />
            </div>
          </div>
          <!-- <li class="form-ul-li half"
              v-if="currentIndex == 5">
            <p class="li-title">单次作业时长：</p>
            <Input v-model="workTime"
                   placeholder="单次作业时长"
                   maxlength="30"
                   v-intLimit
                   clearable
                   class="input-right-5"></Input>
            <span class="li-unit m-r-10">分钟</span>
            <Poptip trigger="hover"
                    content="单个考勤段内作业时长"
                    placement="bottom">
              <Icon custom="i-icon icon-tishi1"
                    size="22"
                    color="#25bb96"
                    class="cursor-pointer" />
            </Poptip>
          </li> -->
          <li class="form-ul-li"
              v-if="currentIndex == 5">
            <p class="li-title">有效时段：</p>
            <DatePicker type="date"
                        class="half"
                        disabled
                        style="margin-right:0"
                        :value="startTime"
                        :options="dateOptions"
                        :editable=false
                        @on-change="onChangeStart"
                        placeholder=""></DatePicker>
            <span style="margin: 0 10px;line-height:32px;">~</span>
            <DatePicker type="date"
                        class="half"
                        :value="endTime"
                        :options="dateOptions"
                        :disabled='endDateDisabled'
                        :editable=false
                        @on-change="onChangeEnd"
                        placeholder=""></DatePicker>
          </li>
          <li class="form-ul-li"
              v-if="currentIndex == 6">
            <p class="li-title">备注：</p>
            <Input v-model="remark"
                   maxlength="-1"
                   :rows="3"
                   type="textarea"
                   placeholder="" />
          </li>
        </ul>
        <div class="flex j-center a-center">
          <Icon type="ios-alert-outline"
                size="20"
                color="#FF0000"
                class="m-r-5" />
          当前批量操作的原始信息将不显示，进行操作后将修改为相同内容。
        </div>
      </div>
    </div>
    <div slot="footer">
      <Button @click.stop="onClickCancel">取消</Button>
      <Button type="primary"
              :loading="loading"
              @click.stop="onClickConfirm">确定</Button>
    </div>
  </Modal>
</template>

<script>
import { mapActions, mapGetters } from 'vuex';
import MyTreeSelect from '@/components/common/MyTreeSelect';
import WorkTimeModal from '@/components/product/admin/modal/work/WorkTimeModal'
import { getTomorrow, formatDate } from '@/utils/dateRangUtil'
export default {
  components: {
    MyTreeSelect,
    WorkTimeModal
  },
  model: {
    prop: 'visible',
    event: 'onChange'
  },
  props: {
    title: {
      type: String,
      default: '修改排班'
    },
    visible: Boolean,
    dataId: String,
    workType: Number
  },
  data () {
    return {
      loading: false,
      menuArr: [
        {
          name: '作业车辆'
        }, {
          name: '作业班组'
        }, {
          name: '作业规则'
        }, {
          name: '处理站'
        }, {
          name: '中转站'
        }, {
          name: '有效时间段'
        }, {
          name: '备注'
        }
      ],
      currentIndex: 0,
      processingStationMenuArr: [
        {
          name: '增加处理站'
        }, {
          name: '删除处理站'
        }
      ],
      currentProcessingStationIndex: 0,
      dateOptions: {
        disabledDate (date) {
          return date && date.valueOf() < Date.now()
        }
      },
      itemMenusArr: [
        {
          name: '增加收集点'
        }, {
          name: '删除收集点'
        }
      ],
      currentItemIndex: 0,
      carItemMenuArr: [
        {
          name: '增加车辆'
        }, {
          name: '删除车辆'
        }
      ],
      currentCarItemIndex: 0,
      endDateDisabled: false,
      type: '',   // 固定作业，机动作业
      workBigType: [], // 作业类型
      workBigTypeId: [], // 作业类型
      carTreeArr: [],
      car: '', // 作业车辆
      carId: '', // 作业车辆id
      driver: '', // 驾驶员
      driverId: '', // 驾驶员id
      carList: [],        // 车辆列表
      carAddList: [],     // 新增车辆列表
      carDeleteList: [],  // 删除车辆列表
      departmentName: '',
      departmentId: '',
      carDisabled: true,
      gather: '',
      gatherId: '',
      disposeList: [],
      gatherList: [],
      group: '', // 作业班组
      groupId: '', // 作业班组
      rule: '', // 作业规则
      ruleId: '', // 作业规则
      period: '', // 作业周期
      count: '2', // 趟次
      oilLoss: '', // 油耗
      waterLoss: '', // 水耗
      workTime: '', // 作业时长
      startTime: '', // 有效时段
      endTime: '', // 有效时段
      remark: '', // 备注
      dispose: '', // 处理站
      disposeId: '', // 处理站id
      disposeTreeArr: [],
      gatherTreeArr: [],
      periodArr: [
        {
          id: 1,
          name: '每天'
        },
        {
          id: 2,
          name: '两天'
        },
        {
          id: 3,
          name: '三天'
        },
        {
          id: 7,
          name: '一周'
        },
      ],
      ruleArr: [],
      groupTreeArr: [],
      workBigTypeArr: [
        {
          children: [],
          id: '74468e83218d866cb341232ffae4618a',
          itemlist: [],
          label: '清扫作业',
          name: '清扫作业',
          type: 'car',
          value: '74468e83218d866cb341232ffae4618a',
        },
        {
          children: [],
          id: '53616f89f4238e20b108eae870a8cdb2',
          itemlist: [],
          label: '洒水作业',
          name: '洒水作业',
          type: 'car',
          value: '53616f89f4238e20b108eae870a8cdb2',
        },
      ],
    }
  },
  watch: {
    dataId (newVal) {
      newVal && this.getDetail()
    },
    visible (newVal) {
      if (newVal) {
        this.getGroupList()
        this.getRuleList()
        this.getFacilityList()
      }
    },
    workType (newVal) {
      if (newVal) {
        this.type = newVal
      }
    },
    currentCarItemIndex () {
      this.carList = []
      this.car = ''
      this.carId = ''
    },
    currentProcessingStationIndex () {
      this.disposeList = []
      this.dispose = ''
      this.disposeId = ''
    },
    currentItemIndex () {
      this.gatherList = []
      this.gather = ''
      this.gatherId = ''
    }
  },
  computed: {
    ...mapGetters({
      'gridNameTreeArr': 'getGridTreeList',
      departmentTreeArr: 'getDepartmentTreeList',
    }),
  },
  mounted () {
    this.init()
  },
  methods: {
    ...mapActions([
      'updateGridTreeList',
      'updateDepartmentTreeList',
    ]),
    init () {
      this.updateGridTreeList()
      this.updateDepartmentTreeList()
      this.timeInit()
    },
    getDetail () {
      // console.log(this.dataId);
      // this.$store.dispatch('getCarDetail', this.dataId).then(res => {
      //   for (let i in res) {
      //     this[i] = res[i]
      //   }
      // })
      // this.disposeList = arr;
    },
    onClickMenuItem (i) {
      this.currentIndex = i
    },
    onClickCarItemMenuItem (i) {
      this.currentCarItemIndex = i
    },
    // 处理站
    onClickProcessingStationMenuItem (index) {
      this.currentProcessingStationIndex = index
    },
    // 中转站
    onClickItemMenuItem (index) {
      this.currentItemIndex = index
    },
    // 修改所属机构
    onChangeDepartment (section) {
      this.carId = ''
      this.car = ''
      this.driverId = ''
      this.driver = ''
      this.departmentId = section.id
      this.departmentName = section.name
      // 获取车辆列表
      this.carDisabled = false
      this.getCarTreeList()
    },
    // 获取车辆列表
    getCarTreeList () {
      let params = {
        carcategory: '83b292821074d284bcf443ad3b0ba92d',
        depid: this.departmentId
      }
      this.$http.getCarDetailTreeList(params).then(res => {
        if (res.code === 200) {
          this.carTreeArr = res.result
        }
      })
    },
    // 选择车辆 单选
    onChangeSelectCar (section) {
      if (section.type == 'car') {
        this.carId = section.id
        this.car = section.name
        this.driverId = section.bindaccount
        this.driver = section.bindaccountname
        this.carList = [{
          id: section.id,
          name: section.name
        }]
      }
    },
    // 删除车
    onClickDeleteCar (index) {
      this.carList.splice(index, 1)
      this.car = this.carList.map(item => {
        return item.name
      }).join()
      this.carId = this.carList.map(item => {
        return item.id
      }).join()
    },
    // 收集点列表
    getFacilityList () {
      this.$http.getFacilityBigTypeAllList({ type: 'facl' }).then(res => {
        if (res.code === 200) {
          console.log(res.result);
          // 中转站/收集站
          let transitIndex = res.result.findIndex(item => {
            return item.name == '中转站'
          })
          let gatherIndex = res.result.findIndex(item => {
            return item.name == '收集站'
          })
          // let faclIdArr = [res.result[transitIndex].id, res.result[gatherIndex].id]
          let faclIdArr = [res.result[transitIndex].id]
          this.$http.getFacilityAllList({ id: faclIdArr.join() }).then(resItem => {
            if (resItem.code === 200) {
              this.gatherTreeArr = resItem.result.content.list
            }
          })

          // 处理站
          let disposeIndex = res.result.findIndex(item => {
            return item.name == '处理站'
          })
          this.$http.getFacilityAllList({ id: res.result[disposeIndex].id }).then(resItem => {
            if (resItem.code === 200) {
              this.disposeTreeArr = resItem.result.content.list
            }
          })
        }
      })
    },
    // 获取作业班组列表
    getGroupList () {
      let params = {
        module: 5
      }
      this.$http.getWorkGroupItemAllList(params).then(res => {
        if (res.code === 200) {
          this.groupTreeArr = res.result.map(item => {
            item.name = item.depName
            item.id = item.depid
            item.type = 'depart'
            if (item.children) {
              item.children = item.children.map(items => {
                items.type = 'group'
                return items
              })
            }
            return item
          })
        }
      })
    },
    // 选择班组
    onChangeGroup (section) {
      if (section.type == 'group') {
        this.groupId = section.workGroupId
        this.group = section.name
      }
    },
    // 获取作业规则列表
    getRuleList () {
      let params = {
        page: 1,
        size: 999,
        module: 5
      }
      this.$http.getWorkRuleList(params).then(res => {
        if (res.code === 200) {
          this.ruleArr = res.result.workRules
        }
      })
    },
    // 作业规则回调
    onChangeRule (data) {
      if (data) {
        this.rule = data.label
        this.ruleId = data.value
      }
    },
    // 有效时段开始时间
    onChangeStart (value) {
      this.startTime = value
    },
    // 有效时段结束时间
    onChangeEnd (value) {
      this.endTime = value
    },
    // 日期选择器赋初始值
    timeInit () {
      let time = new Date()
      // this.startTime = time.getFullYear() + '-01-01'
      this.startTime = getTomorrow()
      this.endTime = time.getFullYear() + '-12-31'
    },
    // 选择中转/收集站
    onChangeGather (section) {
      let idArr = []
      let valueArr = []
      section.forEach(item => {
        if (item.type === 'facl') {
          idArr.push(item.id)
          valueArr.push(item.name)
        }
      })
      this.gatherId = idArr.join()
      this.gather = valueArr.join()

      let dataArr = []
      section.forEach((item) => {
        if (item.type === "facl") {
          dataArr.push(item)
        }
      })
      dataArr.forEach(t => {
        let isFind = false;
        for (let i = 0; i < this.gatherList.length; i++) {
          if (t.id == this.gatherList[i].id) {
            isFind = true;
            break;
          }
        }
        if (!isFind) {
          this.gatherList.push(t);
        }
      })
    },
    // 选择处理站
    onChangeDispose (section) {
      let idArr = []
      let valueArr = []
      section.forEach(item => {
        if (item.type === 'facl') {
          idArr.push(item.id)
          valueArr.push(item.name)
        }
      })
      this.disposeId = idArr.join()
      this.dispose = valueArr.join()

      let dataArr = []
      section.forEach((item) => {
        if (item.type === "facl") {
          dataArr.push(item)
        }
      })
      dataArr.forEach(t => {
        let isFind = false;
        for (let i = 0; i < this.disposeList.length; i++) {
          if (t.id == this.disposeList[i].id) {
            isFind = true;
            break;
          }
        }
        if (!isFind) {
          this.disposeList.push(t);
        }
      })
    },
    // 确定按钮
    onClickConfirm () {
      let carIds = []
      this.carList.forEach((item) => {
        carIds.push(item.id)
      })
      let gatherIds = []
      this.gatherList.forEach((item) => {
        gatherIds.push(item.id)
      })
      let disposeIds = []
      this.disposeList.forEach((item) => {
        disposeIds.push(item.id)
      })
      this.loading = true
      let params = {
        type: 3
      }
      if (this.dataId) params.carPlanIdList = this.dataId.split(',')
      switch (this.currentIndex) {
        case 0:
          params.departmentId = this.departmentId
          params.carId = carIds
          params.flag = this.currentIndex
          break;
        case 1:
          params.groupId = this.groupId
          break;
        case 2:
          params.ruleId = this.ruleId
          break;
        case 3:
          params.disposeId = disposeIds
          params.flag = this.currentProcessingStationIndex
          break;
        case 4:
          params.gatherId = gatherIds
          params.flag = this.currentItemIndex
          break;
        case 5:
          params.startTime = this.startTime
          params.endTime = this.endTime
          break;
        case 6:
          params.remark = this.remark
          break;
      }
      this.$store.dispatch('createOrEditMechanicalCleanPlan', params).then(res => {
        this.$emit('onClickConfirm', params)
        this.$emit('onChange', false)
        this.loading = false
      }).catch(err => {
        this.loading = false
      })
    },
    onClickCancel () {
      this.$emit('onClickCancel')
      this.$emit('onChange', false)
    },
    onChangeVisible (boo) {
      if (!boo) {
        this.$emit('onChange', false)
        this.$emit('update:dataId', '')
        this.resetData()
      }
    },
    resetData () {
      this.workBigType = []
      this.workBigTypeId = []
      this.car = ''
      this.carId = ''
      this.driver = ''
      this.driverId = ''
      this.group = ''
      this.groupId = ''
      this.gather = ''
      this.gatherId = ''
      this.rule = ''
      this.ruleId = ''
      this.period = ''
      this.count = 2
      this.oilLoss = ''
      this.waterLoss = ''
      this.workTime = ''
      this.remark = ''
      this.dispose = ''
      this.disposeId = ''
      this.disposeList = [];
      this.status = 1
      // this.$refs.disposeTreeSelect.resetTreeData();
      this.timeInit()
      this.endDateDisabled = false
      this.departmentName = ''
      this.departmentId = ''
      this.carDisabled = true
      this.currentIndex = 0
      this.currentProcessingStationIndex = 0
      this.currentItemIndex = 0
      this.currentCarItemIndex = 0
    }
  }
}
</script>

<style lang="scss" scoped>
.menu {
  padding: 10px 20px;
  width: 130px;
  border-right: 1px solid #bbbbbb;
  div {
    line-height: 25px;
  }
  .current-menu {
    color: #25bb96;
  }
}
.item-menu {
  padding: 10px 24px;
  width: 120px;
  border-right: 1px solid #bbbbbb;
  div {
    line-height: 30px;
  }
  .current-menu {
    color: #25bb96;
  }
}
.car {
  width: 100%;
  height: 100px;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 4px 7px;
  margin: 0 20px;
  cursor: pointer;
  overflow-y: auto;
  display: flex;
  flex-wrap: wrap;
  .car-item {
    width: 90px;
    height: 24px;
    line-height: 24px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 0 6px 6px 0;
    padding-left: 4px;
    border: 1px solid #e1e4e6;
    border-radius: 3px;
  }
}
</style>